
#include <QFrame>
#include <QKeyEvent>

#include "BlogView.h"
#include "writepageview.h"
#include "WPNetworkEngine.h"
#include "wpconfirmdialog.h"
#include "imagewidget.h"
#include "WPData.h"
#include "utils.h"

static const char* KLocalDraft = "Local draft";

WritePageView::WritePageView(BlogView *parent) : QFrame(parent), iParent(parent)
{
    ui.setupUi(this);
    ui.scrollArea->setWidget(ui.layoutWidget);
    ui.layoutWidget->setContentsMargins(5, 5, 5, 5);
    ui.titleEditor->SetExplanation(tr("Page title"));
    ui.textBrowser->setExplanationText(tr("Tap to begin writing"));

    // Prepare Actions
    QAction* leftSoftKey = new QAction(tr("Save"), this);
    connect(leftSoftKey, SIGNAL(triggered()), this, SLOT(SavePage()));
    leftSoftKey->setSoftKeyRole(QAction::PositiveSoftKey);
    QAction* rightSoftKey = new QAction(tr("Cancel"), this);
    connect(rightSoftKey, SIGNAL(triggered()), this, SLOT(Cancel()));
    rightSoftKey->setSoftKeyRole(QAction::NegativeSoftKey);

    connect(ui.addPhotosButton, SIGNAL(clicked(bool)), this, SLOT(AddPhotosClicked(bool)));
    connect(ui.addVideosButton, SIGNAL(clicked(bool)), this, SLOT(AddVideosClicked(bool)));

    ui.scrollArea->DisableScrollAtWidget(ui.statusEditor->view());

    // Finally add the data for WPCustomViewBasicData
    //
    iTitleText = tr("Edit Page");
    iTabText = tr("Edit");
    iHappyAction = leftSoftKey;
    iSadAction = rightSoftKey;
}

WritePageView::~WritePageView()
{
}

void WritePageView::ResetView (WPPage page)
{
    iAddedImages.clear();
    iAddedVideos.clear();

    // destroy old thumbnails.
    foreach (ImageWidget* thumb, iImageWidgets) {
        delete thumb;
    }
    iImageWidgets.clear();

    // basic items
    ui.titleEditor->setText(page->iTitle);
    ui.textBrowser->reset();
    ui.textBrowser->setText(page->iDescription);
    ui.dateTimeEditor->setDateTime(page->GetLocalTime());
    ui.addPhotosButton->setText(tr("Add photos..."));
    ui.addVideosButton->setText(tr("Add videos..."));

    // statuses
    ui.statusEditor->clear();

    QStringList keyList, valueList;
    QMap<QString, QString>::const_iterator i;

    for (i = iBlog->iPageStatuses.constBegin(); i != iBlog->iPageStatuses.constEnd(); i++)
    {
        keyList.append(i.key());
        valueList.append(i.value());
    }

    ui.statusEditor->addItems(valueList);

    if (page->IsLocal())
    {
        ui.statusEditor->addItem(KLocalDraft);
        ui.statusEditor->setCurrentIndex(ui.statusEditor->count() - 1);

    } 
    else 
    {
        for (int i = 0; i < keyList.count(); ++i)
        {
            if (page->iStatus.compare(keyList.at(i)) == 0)
                ui.statusEditor->setCurrentIndex(i);
        }
    }
    ui.titleEditor->setFocus();
    ui.textBrowser->setFocus(); // maemo5 focus workaround
}

void WritePageView::NewPage(WPDataBlog& aBlog)
{
    iBlog = &aBlog;
    iPage = new WPDataPage(aBlog);
    ResetView(iPage);
}

void WritePageView::EditPage(WPDataBlog& aBlog, WPPage aPage)
{
    iBlog = &aBlog;
    iPage = aPage;
    ResetView(iPage);
}

void WritePageView::SavePage()
{
    if (ui.statusEditor->currentText() == QLatin1String(KLocalDraft)) {
        if (iAddedImages.count() > 0)
            emit ShowWarningNote(tr("Photos are not saved in local drafts. Please re-add photos when publishing the post."));
        if (iAddedVideos.count() > 0)
            emit ShowWarningNote(tr("Videos are not saved in local drafts. Please re-add videos when publishing the post."));

        // just update the local storage
        iPage->UpdateLocal(
                ui.titleEditor->text(),         // title
                ui.textBrowser->text(),         // description
                ui.dateTimeEditor->dateTime()   // local dateCreated
        );
    }
    else
    {
        // save on network
        QList<WPMediaFile> listOfMediaFiles;
        foreach(ImageWidget* image,iImageWidgets)
        {
            WPMediaFile mediaFile(image->FileName());
            mediaFile.rotationAngle = image->RotationAngle();
            mediaFile.size = image->TargetSize();
            mediaFile.alignment = image->Alignment();
            mediaFile.sizeType = image->SizeType();
            listOfMediaFiles.append(mediaFile);
        }

        foreach(QString videoFilename, iAddedVideos)
        {
            listOfMediaFiles.append(WPMediaFile(videoFilename));
        }

        iPage->UpdateStatus(
                ui.titleEditor->text(),         // title
                ui.textBrowser->text(),         // description
                ui.dateTimeEditor->dateTime(),  // local dateCreated
                iBlog->iPageStatuses.key(ui.statusEditor->currentText()),   // status
                listOfMediaFiles
        );
    }
 
    // forget page
    iPage = NULL;
   
    // close
    // XXX: more generic
    iParent->ShowTabbedListView();
#ifdef Q_WS_MAEMO_5
    close();
#endif
}

void WritePageView::AddPhotosClicked(bool aDummy)
{
    Q_UNUSED(aDummy)
    iParent->ShowImageList(iAddedImages, false);
}

void WritePageView::AddVideosClicked(bool aDummy)
{
    Q_UNUSED(aDummy)
    iParent->ShowVideoList(iAddedVideos, false);
}

void WritePageView::ImagesAdded(const QStringList& aFilenames, const QList<QPixmap>& aThumbnails)
{
    iAddedImages = aFilenames;

    RefreshAddPhotoText();

    // refresh image thumbnails.
    if (aFilenames.size() == aThumbnails.size())
    {
        // destroy old thumbnails.
        foreach (ImageWidget* thumb, iImageWidgets)
        {
            delete thumb;
        }
        iImageWidgets.clear();

        // add new ones.
        if (aThumbnails.size() > 0)
        {
            for(int i = 0; i < aFilenames.size(); i++)
            {
                ImageWidget* imageWidget = new ImageWidget(*iBlog,
                                                           aThumbnails.at(i),
                                                           aFilenames.at(i),
                                                           this);
                ui.thumbnails->addWidget(imageWidget);
                iImageWidgets.append(imageWidget);
                connect(imageWidget,SIGNAL(removeClicked(ImageWidget*)),this,SLOT(RemoveImageWidget(ImageWidget*)));
                //ui.textBrowser->setText(ui.textBrowser->text() + "<newimage source=\"" + imageWidget->FileName() + "\"/>\n");
            }
            update();
        }
    }
}

void WritePageView::VideosAdded(const QStringList& aFilenames)
{
    iAddedVideos = aFilenames;

    QString labelText;
    if (iAddedVideos.size() == 0)
        labelText = tr("Add videos...");
    else if (iAddedVideos.size() == 1)
        labelText = tr("Adding 1 new video");
    else
        labelText = tr("Adding %1 new videos").arg(iAddedVideos.size());

    ui.addVideosButton->setText(labelText);
}

void WritePageView::setFocus()
{
    ui.scrollArea->ScrollToTop();
    ui.scrollArea->setFocus();
    
    if (Utils::smallScreen()) {
        ui.titleEditor->setFocus();
    }
}

void WritePageView::Cancel()
{
    if(ui.titleEditor->text().length() || ui.textBrowser->text().length())
    {
        WP_CONFIRM_AND_RETURN_ON_FALSE(iParent);
    }

    iParent->ShowTabbedListView();
}

void WritePageView::RemoveImageWidget(ImageWidget *targetWidget)
{
    int index = iImageWidgets.indexOf(targetWidget);
    int fileNameIndex = iAddedImages.indexOf(targetWidget->FileName());
    if (index >= 0)
    {
        iImageWidgets.removeAt(index);
        targetWidget->hide();
        targetWidget->deleteLater();

    }
    if (fileNameIndex >= 0)
    {
        iAddedImages.removeAt(fileNameIndex);
    }
    RefreshAddPhotoText();
}


void WritePageView::RefreshAddPhotoText()
{
    QString labelText;
    if (iAddedImages.size() == 0) {
        labelText = tr("Add photos") + "...";
    } else if (iAddedImages.size() == 1) {
        labelText = tr("Adding 1 new photo");
    } else {
        labelText = tr("Adding %1 new photos").arg(iAddedImages.size());
    }
    ui.addPhotosButton->setText(labelText);
}
